package com.example.app.config;

import com.example.app.entity.ReqData;
import com.example.app.service.AuthService;
import com.example.app.util.HttpClient;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 短信验证码过滤器链
 */


@Component
@WebFilter
public class AuthCodeFilter extends OncePerRequestFilter {
    private static final Logger LOG = LoggerFactory.getLogger(AuthCodeFilter.class);
    @Autowired
    private AuthConfig authConfig;
    @Autowired
    private AuthService authService;

    /**
     * 过滤状态码地址
     *
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        StringBuffer requestURL = request.getRequestURL();
        String code = request.getParameter(authConfig.getResponseType());
        HttpSession session = request.getSession();
        if (session.getAttribute(AuthConfig.USER_INFO) == null&&!StringUtils.isEmpty(code)) {
            Map<String, String> map = new HashMap<>();
            map.put("authCode", code);
            ReqData sign = authService.getSign(map);
            //验证code
            String postClient = HttpClient.postClient(authConfig.getAuthRest() + "getUserInfo", JSONObject.fromObject(sign).toString());
            LOG.info(postClient);
            JSONObject jsonObject = JSONObject.fromObject(postClient);
            if(!ObjectUtils.isEmpty(jsonObject.get("rsp"))){
                Map<String,String> rsp = jsonObject.getJSONObject("rsp");
                if (rsp!=null){
                    session.setAttribute(AuthConfig.USER_INFO, rsp);
                    session.setAttribute(AuthConfig.OPEN_ID, rsp.get("openid"));
                    session.setAttribute(authConfig.getResponseType(), code);
                }
            }


        }
        filterChain.doFilter(request, response);
    }

}
